﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MyX.DSL
{
    public class XDSLScan
    {
        /// <summary>
        /// 扫描全部的业务逻辑DSL和任务DSL，并初始化执行。
        /// </summary>
        /// <param name="assembly"></param>
        public static void Scan(Assembly assembly)
        {

            if (_assembyls.ContainsKey(assembly.FullName))
                throw new Exception("尝试多次扫描同一个程序集，不允许多次添加DSL");

            var types = assembly.GetTypes();

            var dslTypes = ScanDSL(types);
            var doTypes = ScanDo(types);

            InvokeDSL(dslTypes);
            InvokeDo(doTypes);

            _assembyls[assembly.FullName] = true;
        }

        private static List<Type> ScanDSL(Type[] types)
        {
            return ScanInterface(types, "XIWorkDSL");
        }

        private static List<Type> ScanDo(Type[] types)
        {
            return ScanInterface(types, "XIWorkDoDSL");
        }

        private static List<Type> ScanInterface(Type[] types, string name)
        {
            var result = new List<Type>();
            foreach (var type in types)
            {
                var inter = type.GetInterface(name, true);
                if (inter != null)
                    result.Add(type);
            }
            return result;
        }

        private static void InvokeDSL(List<Type> types)
        {
            foreach (var type in types)
            {
                XIWorkDSL dsl = (XIWorkDSL)Activator.CreateInstance(type);
                dsl.Init();
            }
        }

        private static void InvokeDo(List<Type> types)
        {
            foreach (var type in types)
            {
                XIWorkDoDSL doDsl = (XIWorkDoDSL)Activator.CreateInstance(type);
                doDsl.Run();
            }
        }

        private static Dictionary<string, bool> _assembyls = new Dictionary<string, bool>();
    }
}
